﻿using IM.Easy.Api.AccountManage;
using IM.Easy.Api.Hubs;
using IM.Easy.Core.Attributes;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.LogServices.Dtos;
using IM.Easy.SystemServices.IServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System.Collections.ObjectModel;

namespace IM.Easy.Api.Controllers.System
{
    [ApiController]
    [Route("system/online")]
    public class OnlineController : ControllerBase
    {
        private readonly IHubContext<UserHub> _hubContext;
        private readonly IOnlineService _userManager;

        public OnlineController(IHubContext<UserHub> hubContext, IOnlineService userManager)
        {
            _hubContext = hubContext;
            _userManager = userManager;
        }

        [HttpPost("message")]
        [Api(Name = "发送消息", Perm = "online:user:sendmessage")]
        public async Task<string> SendMessageToUser(string userId, string message)
        {
            var connectionId = _userManager.GetConnectionIdByUserId(userId);
            if (connectionId == null)
            {
                ExceptionUtils.ThrowBusinessException("用户已下线");
            }

            await _hubContext.Clients.Client(connectionId).SendAsync("ReceiveMessage", message);
            return "Message sent.";
        }

        [HttpGet("users")]
        [Api(Name = "获取在线用户", Perm = "online:user:list")]
        public PageResponse<UserOnlineLogDto> GetConnectedUsers([FromQuery] UserOnlineLogQueryDto query)
        {
            var users = _userManager.GetUsers(query);
            return users;
        }
    }

}
